package com.koujun.meinv.server.caipiao;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.koujun.meinv.server.MailReporter;
import com.koujun.meinv.server.StringUtils;

public class CaipiaoChecker implements Runnable {
	private static Logger LOG = Logger.getLogger(CaipiaoChecker.class);

	@Override
	public void run() {
		while (true) {
			try {
				String timer = System.getenv("TIMER");
				if (StringUtils.isEmpty(timer)) {
					timer = "3";
				}
				Thread.sleep(Integer.parseInt(timer) * 60 * 1000);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			try {
				check();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	private List<String> orders = new ArrayList<String>();

	public CaipiaoChecker() {
		for (String id : getIds()) {
			try {
				orders.addAll(aicai.getOrders(id));
				LOG.info("[LOAD] id " + id);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	AiCaiParser aicai = new AiCaiParser();
	MailReporter mail = new MailReporter();

	private String[] getIds() {
		return System.getenv("IDS").split("\\|");
	}

	public void check() {
		try {
			List<String> os = new ArrayList<String>();
			for (String id : getIds()) {
				os.addAll(aicai.getOrders(id));
			}

			StringBuffer buffer = new StringBuffer();
			boolean update = false;
			for (String url : os) {
				if (orders.contains(url)) {
					continue;
				}
				if (update) {
					buffer.append("<br>");
				}
				// send email
				String detail = aicai.getDetail(url);
				if (isExclues(detail)==true) {
					continue;
				}
				buffer.append("<div>" + url + "</div>").append(detail);
				orders.add(url);
				update = true;
			}
			if (update) {
				mail.sendHTML("爱彩网大神更新", buffer.toString(), getTo());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String[] getTo() {
		String tos = System.getenv("CPTZMAIL");
		if (StringUtils.isEmpty(tos)) {
			return new String[] { "63124020@qq.com" };
		}
		String[] split = tos.split("\\|");
		for (int i = 0; i < split.length; i++) {
			split[i] += "@qq.com";
		}
		return split;
	}
	
	public boolean isExclues(String html) {
		String excludes = System.getenv("EXCLUDES");
		if (StringUtils.isEmpty(excludes)) {
			return false;
		}
		for(String ex:excludes.split(",")){
			if(html.indexOf(ex)>-1) return true;
		}
		return false;
	}
}
